import React, { Component } from 'react'
import {connect} from "react-redux";
import {createAddPersonAction} from "../../redux/actions/person";

class Person extends Component {

    state = {
        name: "",
        age: ""
    }

    savePersonData = (type) => {
        return (event) => {
            this.setState({
                [type]: event.target.value
            })
        }
    }

    addPerson = () => {
        this.props.addPerson(this.state)
    }

    render() {
        return (
            <div>
                <h1>我是Person组件</h1>
                <h4>我读取Count组件的和是: {this.props.sum}</h4>
                <input onChange={this.savePersonData('name')} type="text" placeholder="名字"/>
                <input onChange={this.savePersonData('age')} type="text" placeholder="年龄"/>
                <button onClick={this.addPerson}>添加</button>
                <ul>
                    {
                        this.props.persons.map((person, index) => {
                            return <li key={index}>{person.name} --- {person.age}</li>
                        })
                    }
                </ul>
            </div>
        )
    }
}

export default connect(
    state => ({sum: state.count, persons: state.person}), // 映射 state, jsx 中使用则是用 this.props.key
    dispatch => ({
        addPerson: value => dispatch(createAddPersonAction(value)) // 同上 action 的映射, 在 jsx 中使用则是 key
    })
)(Person)